package net.jcip.chapter7;

import com.sky.chapter1.interrupte.Interrupt;

import java.math.BigInteger;
import java.util.concurrent.*;

/**
 * BrokenPrimeProducer
 * <p/>
 * Unreliable cancellation that can leave producers stuck in a blocking operation
 *
 * @author Brian Goetz and Tim Peierls
 */
class BrokenPrimeProducer extends Thread {

    private final BlockingQueue<BigInteger> queue;
    private volatile boolean cancelled = false;

    private BrokenPrimeProducer(BlockingQueue<BigInteger> queue) {
        this.queue = queue;
    }

    public void run() {
        try {
            BigInteger p = BigInteger.ONE;
            while (!cancelled){
                queue.put(p = p.nextProbablePrime());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void cancel() {
        cancelled = true;
    }


    public static void main(String[] args){
        BlockingQueue<BigInteger> blockingQueue = new LinkedBlockingQueue<>();
        BrokenPrimeProducer brokenPrimeProducer = new BrokenPrimeProducer(blockingQueue);
        brokenPrimeProducer.start();

        try {
            TimeUnit.MILLISECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            brokenPrimeProducer.cancel();

        }

    }

}



